import React from 'react';
import { Form, Input, Select, DatePicker, Button, Row, Col } from 'antd';
import './index.css';

const { Option } = Select;

const SearchForm = ({ 
  form,                // Form 实例
  fields = [],         // 搜索字段配置
  onSearch,            // 搜索回调
  layout = 'inline',   // 表单布局
}) => {
  // 渲染表单项
  const renderFormItem = (field) => {
    switch (field.type) {
      case 'input':
        return (
          <Input 
            placeholder={field.placeholder} 
            allowClear 
            style={{ width: '180px', ...field.style }}
            {...field.props}
          />
        );
      case 'select':
        return (
          <Select 
            placeholder={field.placeholder}
            allowClear
            style={{ width: '180px', ...field.style }}
            {...field.props}
          >
            {field.options?.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        );
      case 'date':
        return (
          <DatePicker 
            placeholder={field.placeholder}
            style={{ width: '180px', ...field.style }}
            allowClear
            {...field.props}
          />
        );
      case 'button':
        return (
          <Button 
            type={field.buttonType || 'default'}
            htmlType={field.htmlType || 'button'}
            onClick={field.onClick}
            loading={field.loading || false}
            style={field.style}
          >
            {field.label}
          </Button>
        );
      default:
        return null;
    }
  };

  return (
    <div className="search-form-container">
      <Form 
        form={form}
        layout={layout}
        onFinish={onSearch}
      >
        <Row gutter={[16, 16]}>
          {fields
          .filter((field) => field.type !== 'button') // 过滤掉按钮
          .map((field) => (
            <Col span={6} key={field.name || field.label}>
              <Form.Item
               name={field.name}
               label={field.label}
               rules={field.rules}
              >
                {renderFormItem(field)}
              </Form.Item>
            </Col>
          ))}
          <Col span={6}>
            <Form.Item>
                 <div style={{ display: 'flex', justifyContent: 'center' }}>
                 {fields
                    .filter((field) => field.type === 'button') // 仅渲染按钮
                    .map((field) => (
                      <span key={field.label}>
                        {renderFormItem(field)}
                      </span>
                    ))
                  }
                 </div>
            </Form.Item>
          </Col>
        </Row>
       
      </Form>
    </div>
  );
};

export default SearchForm;